# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 -------------------------------------------------
    File Name:     config.py
    Description:   配置和变量管理
 -------------------------------------------------
 """
import json
import os
from pathlib import Path


class ConfigManager:
    """配置管理器"""

    def __init__(self, config_path=None, env=None):
        """初始化配置管理器"""
        self.config_data = {}
        self.config_path = config_path
        self.env = env or os.environ.get("TEST_ENV", "dev")
        self.load_config()

    def load_config(self):
        """加载配置文件"""
        # 加载默认配置
        default_config = self._load_json_file(Path("config/default.json"))

        # 加载环境特定配置
        env_config = self._load_json_file(Path(f"config/env/{self.env}.json"))

        # 合并配置
        self.config_data = {**default_config, **env_config}

        # 如果指定了额外配置路径，也加载它
        if self.config_path:
            custom_config = self._load_json_file(Path(self.config_path))
            self.config_data = {**self.config_data, **custom_config}

    @staticmethod
    def _load_json_file(file_path):
        """加载JSON文件"""
        try:
            if file_path.exists():
                with open(file_path, 'r', encoding='utf-8') as f:
                    return json.load(f)
        except Exception as e:
            print(f"加载配置文件 {file_path} 失败: {e}")
        return {}

    def get(self, key, default=None):
        """获取配置值"""
        return self.config_data.get(key, default)

    def set(self, key, value):
        """设置配置值"""
        self.config_data[key] = value
        return self

    def update(self, data):
        """批量更新配置"""
        self.config_data.update(data)
        return self


class VariableManager:
    """变量管理器"""

    def __init__(self):
        """初始化变量管理器"""
        self.variables = {}

    def set(self, name, value):
        """设置变量"""
        self.variables[name] = value
        return self

    def get(self, name, default=None):
        """获取变量"""
        return self.variables.get(name, default)

    def update(self, data):
        """批量更新变量"""
        self.variables.update(data)
        return self

    def clear(self):
        """清除所有变量"""
        self.variables.clear()
        return self
